package com.example.question.bt.backtrack1;

import java.util.ArrayList;
import java.util.List;

/**
 * @Date 2023-07-16
 * @Author Jonathan
 */
public class Code04_77 {
    public static void main(String[] args) {
        Code04_77 code = new Code04_77();
        System.out.println(code.combine(4, 2));
    }

    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        if (n < 0 || k > n) {
            return res;
        }
        boolean[] visited = new boolean[n];
        List<Integer> combinations = new ArrayList<>();
        dfs(n, k, 1, combinations, visited, res);
        return res;
    }

    private void dfs(int n, int k, int start, List<Integer> combination, boolean[] visited, List<List<Integer>> res) {
        // 有k个值了就回溯
        if (combination.size() == k) {
            res.add(new ArrayList<>(combination));
            return;
        }
        for (int i = start; i <= n; i++) {
            // 剪枝 不使用重复的元素
//            if (visited[i - 1]) {
//                continue;
//            }
            combination.add(i);
//            visited[i - 1] = true;
            dfs(n, k, i + 1, combination, visited, res);
//            visited[i - 1] = false;
            combination.remove(combination.size() - 1);
        }
    }
}
